package cn.yqm.modules.admin.controller;

import cn.yqm.common.ResultResponse;
import cn.yqm.common.YqmProperties;
import cn.yqm.common.factory.UploadFactory;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 上传
 *
 * @author weiximei
 * @domain www.yqmshop.cn
 * @since 2023/8/20
 */
@Slf4j
@AllArgsConstructor
@RequestMapping("/upload")
@Controller
public class UploadController {

    private final YqmProperties yqmProperties;

    @PostMapping("")
    @ResponseBody
    public ResultResponse upload(@RequestParam("file") MultipartFile file) {
        try (InputStream is = file.getInputStream();
             ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            IOUtils.copy(is, os);
            byte[] bytes = os.toByteArray();
            String url = UploadFactory.getSingle(yqmProperties.getFile().getStoreType()).upload(bytes, file.getOriginalFilename());
            Map<String, Object> map = Maps.newHashMap();
            map.put("url", url);
            return ResultResponse.success("文件上传成功", map);
        } catch (IOException e) {
            log.error("文件上传发生异常 -> {}", e.getMessage());
            return ResultResponse.error("文件上传失败");
        }

    }
}
